<template>
	<div>
		<!-- 面包屑头部 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
		  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
		  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
		  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片视图 -->
		<el-card>
			<!-- 点击添加角色 -->
			<el-row>
				<el-col :span="8">
					<el-button @click="addRolesDialog = true" type="primary">添加角色</el-button>
				</el-col>
			</el-row>
			<!-- 列表区域 -->
			<el-table border stripe :data="rolesList">
				<!-- 展开列 -->
				<el-table-column type="expand">
					<template slot-scope="scope">
						<el-row :class="['dbdottom',i1 === 0 ? 'bdtop' : '','vcenter']" v-for="(item1, i1) in scope.row.children" :key='item1.id'>
							<!-- 渲染一级权限 -->
							<el-col :span="5">
								<el-tag @close='removeRightById(scope.row, item1.id)' closable>{{item1.authName}}</el-tag>
								<i class="el-icon-caret-right"></i>
							</el-col>
							<!-- 渲染二，三级权限 -->
							<el-col :span="19">
								<!-- 二级权限 -->
								<el-row :class="[i2 === 0 ? '' : 'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key='item2.id'>
									<el-col :span="6">
									<el-tag @close='removeRightById(scope.row, item2.id)' closable type='success'>{{item2.authName}}</el-tag>
									<i class="el-icon-caret-right"></i>
									</el-col>
									<!-- 三级权限 -->
									<el-col :span="18">
										<el-tag @close='removeRightById(scope.row, item3.id)' closable type='warning' v-for="item3 in item2.children" :key='item3.id'>
											{{item3.authName}}
										</el-tag>
									</el-col>
								</el-row>
								
							</el-col>
							
						</el-row>
					</template>
				</el-table-column>
				<!-- 索引列 -->
				<el-table-column type="index" label="#"></el-table-column>
				<el-table-column label="角色名称" prop="roleName"></el-table-column>
				<el-table-column label="角色描述" prop="roleDesc"></el-table-column>
				<el-table-column label="操作" width="300px">
					<template slot-scope='scope'>
						<el-button @click='editFormList(scope.row.id)' size='mini' type="primary" icon="el-icon-edit">编辑</el-button>
						<el-button @click="deleteFormList(scope.row.id)" size='mini' type="danger" icon="el-icon-delete">删除</el-button>
						<el-button size='mini' type="warning" icon="el-icon-setting" @click='showsetRightDialog(scope.row)'>分配权限</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		
		<!-- 添加用户对话框 -->
		<el-dialog
		  title="添加用户"
		  @close="addDialogClosed"
		  :visible.sync="addRolesDialog"
		  width="50%"
		 >
			<!-- 内容区域 -->
			<el-form :model="adduser" :rules="adduserRules" ref="addRef" label-width="100px">
			  <el-form-item label="角色名称" prop="roleName">
			    <el-input v-model="adduser.roleName"></el-input>
			  </el-form-item>
			  <el-form-item label="角色描述" prop="roleDesc">
			    <el-input v-model="adduser.roleDesc "></el-input>
			  </el-form-item>
			 </el-form>
		  <!-- 底部按钮 -->
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="addRolesDialog = false">取 消</el-button>
		    <el-button type="primary" @click="addRoles">确 定</el-button>
		  </span>
		</el-dialog>
		
		<!-- 修改用户对话框 -->
		<el-dialog
		  title="修改用户"
		  :visible.sync="editDialogVisible"
		  width="50%"
		  @close="editDialogClose"
		  >
		  <!-- 内容区域 -->
		  <el-form :model="editForm" :rules="editRules" ref="editRef" label-width="100px">
		    <el-form-item label="角色名称" prop="roleName">
		      <el-input v-model="editForm.roleName"></el-input>
		    </el-form-item>
		    <el-form-item label="角色描述" prop="roleDesc">
		      <el-input v-model="editForm.roleDesc"></el-input>
		    </el-form-item>
		   </el-form>
		   <!-- 底部区域 -->
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="editDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="editUserInfo">确 定</el-button>
		  </span>
		</el-dialog>
		
		<!-- 分配权限对话框 -->
		<el-dialog
		  title="分配权限"
		  :visible.sync="setRightDialogVisible"
		  width="50%"
		  @close="setRightDialogClosed"
		  >
		  <!-- 主体树形空间内容 -->
		  <el-tree ref="treeRef" lt-checked-keys='defKeys' default-expand-all show-checkbox node-key='id' :data="rightslist" :props="treeProps"></el-tree>
		  <!-- 底部 -->
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="setRightDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="allotRithrs">确 定</el-button>
		  </span>
		</el-dialog>
	</div>
</template>

<script>
	export default{
		data() {
			return{
				// 所有角色列表
				rolesList:[],
				// 添加用户对话框关闭与隐藏
				addRolesDialog:false,
				// 添加用户内容赋值
				adduser:{
					roleName:'',
					roleDesc:''
				},
				// 添加用户表单验证
				adduserRules:{
					roleName:[
					{ required: true, message: '请输入角色名称', trigger: 'blur' },
					{ min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
					],
					roleDesc:[
					{ required: true, message: '请输入角色描述', trigger: 'blur' },
					{ min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
					]
				},
				// 修改用户显示与隐藏
				editDialogVisible:false,
				// 修改用户赋值区域
				editForm:{},
				// 修改用户校验
				editRules:{
				roleName:[
				{ required: true, message: '请输入角色名称', trigger: 'blur' },
				{ min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
				],
				roleDesc:[
				{ required: true, message: '请输入角色描述', trigger: 'blur' },
				{ min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
				]	
				},
				// 分配权限对话框显示与隐藏
				setRightDialogVisible:false,
				// 所有权限数据
				rightslist:[],
				// 树形控件绑定对象
				treeProps: {
				children: 'children',
				label: 'authName'
				},
				// 默认选中的树植
				defKeys:[],
				// 当前即将分配权限id
				roleId:'',
			}
		},
		created() {
			this.getRolesList()
		},
		methods:{
			async getRolesList(){
		  const {data:res} = await this.$http.get('roles')
		  if(res.meta.status !== 200){
			  return this.$message.error('获取角色列表失败')
		  }
		  this.rolesList = res.data
		  // console.log(res)
			},
			// 重置表单校验
			addDialogClosed(){
				this.$refs.addRef.resetFields();
			},
			// 添加角色确认按钮
			addRoles(){
				// 预校验
				this.$refs.addRef.validate(async valid =>{
					// console.log(valid)
					if(!valid){
						return this.$Message.error('表单添加信息有误')
					}
					const {data:res} = await this.$http.post('roles',this.adduser)
					// console.log(res)
					if(res.meta.status !==201){
						return this.$Message.error('添加角色失败')
					}
					this.getRolesList()
					this.addRolesDialog = false
					this.$Message.success('添加用户成功')
				})
			},
			// 修改对话框关闭重置
			editDialogClose(){
				this.$refs.editRef.resetFields()
			},
			// 编辑按钮
			async editFormList(id){
				// console.log(id)
				this.editDialogVisible = true
				// 获取对应值赋值
				const {data:res} = await this.$http.get('roles/'+id)
				// console.log(res)
				if(res.meta.status !==200){
					return this.$message.error('获取信息失败')
				}
				this.editForm = res.data
			},
			// 编辑对话框确定按钮
			editUserInfo(id){
				// 表单验证
				this.$refs.editRef.validate(async valid =>{
					if(!valid){
						return this.$Message.error('请输入正确的内容')
					}
					const {data:res} = await this.$http.put('roles/' +this.editForm.roleId, {roleName:this.editForm.roleName,roleDesc:this.editForm.roleDesc})
					if(res.meta.status !==200){
						return this.$Message.error('修改角色失败')
					}
					this.getRolesList()
					this.editDialogVisible = false
					return this.$Message.success('修改角色成功')
				})
			},
			// 删除按钮点击
			async deleteFormList(id){
				const ConFirm = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
				          confirmButtonText: '确定',
				          cancelButtonText: '取消',
				          type: 'warning'
				        }).catch(err =>{
							return err
						})
						if(ConFirm !== 'confirm'){
							return this.$Message.error('取消删除')
						}
						const {data:res} = await this.$http.delete('roles/'+ id)
						if(res.meta.status !=200){
							return this.$message.error('删除失败')
						}
						this.$message.success('删除成功！')
						this.getRolesList()
						
			},
			// 根据Id删除对应el-tag标签关闭
			async removeRightById(role, rightId){
				// 弹框提示是否删除
				const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
				          confirmButtonText: '确定',
				          cancelButtonText: '取消',
				          type: 'warning'
				        }).catch(err => err)
					if(confirmResult !=='confirm'){
						return this.$Message.error('取消了删除')
					}
					const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
					if(res.meta.status !==200){
						return this.$message.error('删除权限失败')
					}
						role.children = res.data
						return this.$message.success('删除权限成功')
			},
			// 展示分配权限对话框
			 async showsetRightDialog(role){
				 this.roleId  = role.id
				 this.gitLeafKeys(role,this.defKeys)
				
				// 获取所有权限信息
				
				const {data:res} = await this.$http.get('rights/tree')
				// console.log(res)
					if(res.meta.status !== 200){
						return this.$Message.error('获取权限信息失败')
					}
					this.rightslist = res.data
					// 展开对话框
					this.setRightDialogVisible = true
					// console.log(this.rightslist)				
			},
			// 通过递归的形式，获取角色下所有三级权限，保存到数组
			gitLeafKeys(node, arr){
				// console.log(node)
				if(!node.children){
					return arr.push(node.id)
				}
				node.children.forEach(item =>
				this.gitLeafKeys(item, arr)
				)
			},
			// 监听非配权限对话框的关闭
			setRightDialogClosed(){
			this.defKeys = []	
			},
			// 点击分配权限
			async allotRithrs(){
				const keys = [
					...this.$refs.treeRef.getCheckedKeys(),
					...this.$refs.treeRef.getHalfCheckedKeys(),
				]
				// console.log(keys)
				const idStr = keys.join(',')
				
				const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
				if(res.meta.status !== 200){
					return this.$message.error('分配权限失败')
				}
				this.$Message.success('分配权限成功')
				this.getRolesList()
				this.setRightDialogVisible = false
			
			},
		}
	}
</script>

<style lang="less" scoped="scoped">
.el-tag{
	margin: 10px;
}
.bdtop{
	border-top: 1px solid #eee;
}
.dbdottom{
	border-bottom: 1px solid #eee;
}
.vcenter{
	display: flex;
	align-items: center;
}
</style>
